import java.util.*;
/**
 * @program: lleetcode003
 * @author: JCM
 * @create: 2022-11-25 08:47
 * @description: 无重复字符的最长子串
 **/
public class LeetCode003 {

    /**
     * 暴力枚举
     * @param s
     * @return 返回子串的长度
     */
    public int lengthOfLongestSubstring(String s) {
        int len = 0;
        for(int i=0; i < s.length(); i++) {
            StringBuffer sb = new StringBuffer();
            int j = i;
            for(;j < s.length();j++) {
                String ch = s.substring(j,j+1);
                if(sb.indexOf(ch) != -1) {
                    break;
                }else {
                    sb.append(ch);
                    if(sb.length() > len) {
                        len = sb.length();
                    }
                }
            }
            if(j == s.length()) break;
        }
        return len;
    }
}
class Solution {
    /**
     * 滑动窗口
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {
        Map<Character,Integer> map = new HashMap<Character,Integer>();
        int max = 0;
        int left = 0;
        for(int i = 0; i < s.length();i++) {
            char ch = s.charAt(i);
            if(map.containsKey(ch)) {
                //窗口向右滑动，使窗口内的数据有效
                left = Math.max(left,map.get(ch)+1);
            }
            map.put(ch,i);
            //更新最大长度
            max = Math.max(max,i-left+1);
        }
        return max;
    }
}
